package com.sfteam.bmw.api;

import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.ext.kit.SessionIdKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.sfteam.bmw.model.User;
import com.sfteam.bmw.utils.JsonUtil;
import com.sfteam.bmw.utils.WeiXinReqUtil;
import com.sfteam.bmw.vo.AjaxResult;

/**
 * 用户登录api
 * 
 * @author knight322
 *
 */
public class WeiXinApi extends Controller {

	static Log logger = Log.getLog(WeiXinApi.class);

	private AjaxResult result = new AjaxResult();

	/**
	 * 登录
	 */
	public void login() {
		String code = getPara("code");
		String rtl = WeiXinReqUtil.jscode2session(code);
		Map<String, String> map = JsonUtil.toJsonMap(rtl);
		// 将session_key以及openid存入session
		String token = SessionIdKit.me().generate(getRequest());
		System.out.println("token========" + token);
		Cache userCache = Redis.use();
		String openId = map.get("openid");
		userCache.set(token + "_sk", map.get("session_key"));
		userCache.set(token + "_op", openId);
		User user = User.dao.findFirst("select * from t_user where openId = ?", openId);
		if(!StrKit.notNull(user)){
			user = new User();
			user.set("userno", "");// 会员号
			user.set("openid", openId);// 用户标识
			user.save();
		}
		result.success(token);
		renderJson(result);
	}
}
